package net.huanger.gametools.mapeditor.ui;

import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.image.ImageProducer;
import java.awt.image.MemoryImageSource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import net.huanger.gametools.mapeditor.model.MapModel;

import com.google.gson.Gson;

public class MUtils
{
  public static   Gson gson=new Gson();
  public static final int OUT_LIMIT = -1;
  public static Point cellToPoint(int cell,int row,int column,int unit) throws OutLimitException{
    int t_row=cell/column;
    if(t_row>row){
        throw new OutLimitException(String.format("row %d out of %d\n", t_row,row));
    }
    int t_column=cell%column;
    return new Point(t_column*unit, t_row*unit);
  }
  public static int pointToCell(Point point,int row,int column,int unit){
    int t_row=point.y/unit;
    int t_column=point.x/unit;
    if(t_row>=row||t_column>=column)
    {
      return OUT_LIMIT;
    }
    return t_row*column+t_column;
  }
  
  public static final Image MENG_BAN=getMengBan();
  public static void storeMapData(MapModel mm,File file) throws IOException{
    String json = gson.toJson(mm);
    FileWriter out=new FileWriter(file);
    out.write(json);
    out.close();
  }
  private static Image getMengBan()
  {
      int unit=16;
      int[]pix=new int[unit*unit];
      for(int i=0;i<pix.length;i++){
        pix[i]=(128<<24)|(255<<16)|(0<<8)|0;
      }
      ImageProducer  producer=new MemoryImageSource(unit,unit,pix, 0, unit);
//      BufferedImage img=new BufferedImage(unit,unit,BufferedImage.TYPE_INT_ARGB);
//      img.setRGB(0, 0, unit, unit, pix, 0, unit);
      Image img=Toolkit.getDefaultToolkit().createImage(producer);
      return img;
  }
  public static MapModel loadMapData(File file) throws FileNotFoundException{
    FileReader json = new FileReader(file);
    MapModel mm=gson.fromJson(json, MapModel.class);
    return mm;
  }
}
